<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @todo 	用户控制器
 * @copyright	
 * @author shiqiliang<ozil1987@gmail.com>
 * @package controllers
 * @subpackage mysite
 * @version 2013-8-1
 */
class User extends MY_APP_Controller{
	
	function __construct() {
		parent::__construct();
		$this->loadModel('User_model','User');
	}
	
	/**
	 *front login
	 */
	function login(){
		$redirect = getRedirect(site_url());
		if(!empty($_POST)){
			$data = $this->input->post(null,true);
			$user = $this->User->doLogin($data['user']['email'],$data['user']['password'],false);
			if($user!==false){
				$newdata['userId']		= $user->id;
				$newdata['trueName']	= $user->username;
				$newdata['userName']	= $user->username;
				$newdata['isAdmin']	= $user->is_admin;
				//if(!empty($user->role_ids)) $newdata['roles']	= $user->role_ids==1?1:explode(',',$user->role_ids);
				//记住我
				/*if(isset($data['rememberme']) && $data['rememberme']=='forever'){
					$this->config->set_item('sess_expiration', 0);
				}*/
				$this->session->set_userdata($newdata);
				redirect($redirect);
				//$mes = 'mes_success';
				//return $this->showMessage($mes,$redirect);
			} else {
				$this->lang->load('user');
				$this->display('user/login', array('errorMessage'=>$this->lang->line($this->User->_error)));
			}
		}
		
		$this->display();
	}
	
	private function oauth($provider = ''){
		$this->config->load('oauth2');
		$allowed_providers = $this->config->item('oauth2');
		if ( ! $provider OR ! isset($allowed_providers[$provider]))
		{
			exit('暂不支持'.$provider.'方式登录.');
        	$this->session->set_flashdata('info', '暂不支持'.$provider.'方式登录.');
            redirect();
            return;
		}
		$this->load->library('oauth2');
		$provider = $this->oauth2->provider($provider, $allowed_providers[$provider]);
        $args = $this->input->get();
        if ($args AND !isset($args['code']))
        {
        	exit('授权失败了,可能由于应用设置问题或者用户拒绝授权.<br />具体原因:<br />'.json_encode($args)); 
          	$this->session->set_flashdata('info', '授权失败了,可能由于应用设置问题或者用户拒绝授权.<br />具体原因:<br />'.json_encode($args));
            redirect();
            return;
        }
        $code = $this->input->get('code', TRUE);
		if ( ! $code)
		{
                  try
                  {
			         $provider->authorize();
                  }
                  catch (OAuth2_Exception $e)
                  {
                  	exit('操作失败<pre>'.$e.'</pre>');
                  	$this->session->set_flashdata('info', '操作失败<pre>'.$e.'</pre>');
                  }
		}
		else
		{
			try
			{
				$token = $provider->access($code);
	        	$sns_user = $provider->get_user_info($token);
				if (is_array($sns_user))
				{
					var_dump($sns_user);exit;
                    $this->session->set_flashdata('info', '登录成功');
					$this->session->set_userdata('user', $sns_user);
                    $this->session->set_userdata('is_login', TRUE);
				}
				else
				{
					exit('获取用户信息失败');
                    $this->session->set_flashdata('info', '获取用户信息失败');
				}
			}
			catch (OAuth2_Exception $e)
			{
				exit('操作失败<pre>'.$e.'</pre>');
                $this->session->set_flashdata('info', '操作失败<pre>'.$e.'</pre>');
			}
		}
        redirect();
	}
	
	
	/**
	 * 注册
	 */
	function register() {
		if ($this->input->post(null,true)) {
			return $this->save('user/create');
		} else {
			$this->display();
		}
	}
	
	/**
	 * 添加用户
	 */
	private function save( $type='' ) {
		$redirect = site_url();
		$this->load->library('form_validation');
		$this->lang->load('template');
		
		if ($this->form_validation->run($type) == FALSE) {
			$this->display('user/register', array('errorMessage'=>validation_errors()));
			return false;
		}
		$data = $this->input->post(null,true);
		$this->lang->load('user');
		if (!captcha_check($data['captcha'])) {
			$this->display('user/register', array('errorCaptcha'=>$this->lang->line('error_captcha')));
			return false;
		}
		$users['username'] = $data['username'];
		$users['password'] = $data['password'];
		$users['email'] = $data['email'];
		if (($user_id = $this->User->save($users))!==false) {
			redirect('user/login');
		} else {
			$this->display('user/register', array('errorMessage'=>$this->lang->line($this->User->_error)));
			return false;
			//return $this->showMessage($this->User->_error); 
		}
	}
	
	/**
	 * front logout
	 */
	function logout(){
		$this->session->sess_destroy();
		$mes = 'mes_success';
		return $this->showMessage($mes,site_url());
	}
	
	public function check($value,$field){
		$where = array(
			$field=>$value,
		);
		$result = $this->User->findByField($where);
		$currrId = $this->input->post('id',true);
		if(!empty($result) && $result[0]['id']!=$currrId){
			$this->form_validation->set_message('check', '%s 已经存在!');
			return false;
		}
		return true;
	}
	
	public function captcha() {
		captcha();
	}
}